/**
 * 
 */
package com.whf15.o2o.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.whf15.o2o.dao.ProductCategoryDao;
import com.whf15.o2o.dao.ProductDao;
import com.whf15.o2o.dto.ProductCategoryExecution;
import com.whf15.o2o.entity.ProductCategory;
import com.whf15.o2o.enums.ProductCategoryStateEnum;
import com.whf15.o2o.exceptions.ProductCategoryOperationException;
import com.whf15.o2o.service.ProductCategoryService;


/** 
* @author 作者 :whfo 
* @version 创建时间：2021年6月29日 下午3:47:52 
* 类说明 
*/

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService{
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ProductCategoryDao productCategoryDao;

	@Override
	public List<ProductCategory> getProductCategoryList(long shopId) {
		return productCategoryDao.queryProductCategoryList(shopId);
	}

	
	@Override
	@Transactional
	public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategories)
			throws ProductCategoryOperationException {
		if(productCategories != null && productCategories.size() > 0) {
			try {
				int effectedNum = productCategoryDao.batchInsertProductCategory(productCategories);
				if(effectedNum <= 0) {
					throw new ProductCategoryOperationException("店铺类别创建失败");
				}else {
					return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
				}
			} catch (Exception e) {
				throw new ProductCategoryOperationException("batchAddProductCategory error"+e.getMessage());
			}
		}else {
			return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);

		}
	}


	
	@Override
	@Transactional
	public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId)
			throws ProductCategoryOperationException {
		// TODO 将此商品类别下的商品的类别id置为空
		//1.解除tb_product里的商品与该productcategoryId的关联
		try {
			int effectedNum = productDao.updateProductCategoryToNull(productCategoryId);
			if(effectedNum < 0 ) {
				throw new ProductCategoryOperationException("商品类别更新失败");
			}
		} catch (Exception e) {
			throw new ProductCategoryOperationException("deleteProductCategory error"+e.getMessage());
		}
		//2.再删除productCategory
		try {
			int effectedNum = productCategoryDao.deleteProductCategory(productCategoryId, shopId);
			if(effectedNum <= 0) {
				throw new ProductCategoryOperationException("店铺类别删除失败");
			}else {
				return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
			}
		} catch (Exception e) {
			throw new ProductCategoryOperationException("deleteProductCategory error"+e.getMessage());
		}
		
	}

}
